import './assets/main.css'

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import pinia from './store'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import { resolveImage } from '@/utils/request'

import { useUserStore } from './store/modules/user'
import { initAuth, startTokenCheck } from '@/utils/auth'

const app = createApp(App)

for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component)
}

app.use(router)
app.use(pinia)
app.use(ElementPlus)

initAuth()

startTokenCheck()

const userStore = useUserStore()
userStore.initUserFromStorage()

app.directive('img-fallback', {
  mounted(el) {
    const PLACEHOLDER = ''
    let triedRaw = false
    el.addEventListener('error', () => {
      const src = el.getAttribute('src') || ''
      if (!triedRaw) {
        triedRaw = true
        try {
          const m = src.match(/\/proxy\/image\?url=([^&]+)/)
          const raw = m ? decodeURIComponent(m[1]) : src
          if (raw && raw !== src) el.setAttribute('src', raw)
          else el.setAttribute('src', PLACEHOLDER)
        } catch {
          el.setAttribute('src', PLACEHOLDER)
        }
      } else {
        el.setAttribute('src', PLACEHOLDER)
      }
    })
  }
})

app.mount('#app')
